//
//  WNInviteVC.swift
//  WalkNovel
//
//  Created by Kevin on 2023/12/20.
//

import UIKit

class WNInviteVC: WNBaseVC {
    
    lazy var invTabView: WNTableView = {
        let tab = WNTableView(frame: .zero, style: .grouped)
        tab.register(InviteRewardsCell.self, forCellReuseIdentifier: InviteRewardsCell.identifier)
        tab.register(InviteTaskCell.self, forCellReuseIdentifier: InviteTaskCell.identifier)
        tab.backgroundColor = .init(named: "white_F7F7F7")
        tab.delegate = self
        tab.dataSource = self
        return tab
    }()
    
    var inviteModel: InviteModel? {
        didSet {
            invTabView.reloadData()
        }
    }

    // 必须是全局变量（坑）
    var docVC: UIDocumentInteractionController?
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func viewConfig() {
        view.addSubview(invTabView)
        invTabView.snp.makeConstraints { make in
            make.top.equalTo(NaviTotalHeight+20)
            make.left.bottom.right.equalTo(0)
        }
    }
    
    override func dataConfig() {
        pageName = "Invite"
        navView.titleName = "Invite friends"
        inviteCodeRequest()
    }
}

extension WNInviteVC: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return section == 0 ? 3 : 3
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: InviteRewardsCell.identifier, for: indexPath) as! InviteRewardsCell
            cell.rewardsType = indexPath.item
            return cell
        }else {
            let cell = tableView.dequeueReusableCell(withIdentifier: InviteTaskCell.identifier, for: indexPath) as! InviteTaskCell
            cell.taskType = indexPath.item
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return indexPath.section == 0 ? 76 : 120
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section == 0 {
            let view = InviteRewardsView()
            view.codeLabel.text = inviteModel?.code
            view.inviteClosure = { [weak self] str in
                if str == "invite" {
                    let url = URL(string: "https://apps.apple.com/app/id1618868786")
                    self?.docVC = UIDocumentInteractionController(url: url!)
                    self?.docVC?.presentOptionsMenu(from: self!.view.bounds, in: self!.view, animated: true)
                }
                if str == "inviter" {
                    showSpringType(.inviteCode)
                    WNSpringView.shared.isRightClosure = { isRight in
                        if isRight {
                            self?.verifyCodeRequest(WNSpringView.shared.inviteTF.text ?? "")
                        }
                    }
                }
            }
            return view
        }else {
            let view = InviteTaskView()
            view.leftCount.text = "\(inviteModel?.count ?? 0)"
            view.rightCount.text = "\(inviteModel?.gold ?? 0)"
            return view
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return section == 0 ? scaleWidth(210)+234 : 136
    }
}

extension WNInviteVC {
    
    func inviteCodeRequest() {
        provider_invite.rx.request(.getInviteCode)
            .asObservable().mapModel(BaseModel<InviteModel>.self)
            .subscribe(onNext: { [weak self] (model) in
                guard model.code == 0 else {
                    self?.wn_toast(model.msg ?? "")
                    return
                }
                if let data = model.data {
                    self?.inviteModel = data
                }
            }, onError: { [weak self] (error) in
                self?.wn_toast("Check the network connection")
            }).disposed(by: rx.disposeBag)
    }
    
    func verifyCodeRequest(_ code: String) {
        provider_invite.rx.request(.verifyCode(code))
            .asObservable().mapModel(BaseModel<Any>.self)
            .subscribe(onNext: { [weak self] (model) in
                guard model.code == 0 else {
                    self?.wn_toast(model.msg ?? "")
                    return
                }
                self?.wn_toast(model.msg ?? "Verification successful")
            }, onError: { [weak self] (error) in
                self?.wn_toast("Check the network connection")
            }).disposed(by: rx.disposeBag)
    }
}
